<template>
  <ul class="list">
    <li class="item"
        v-for="item
                of
                letters" :key="item"
        @click="goTopage(item)"
        @touchstart="handleTouchStart"
        @touchmove="handleTouchMove($event)"
        @touchend="handleTouchEnd"
        :ref="item">{{item}}</li>
  </ul>
</template>

<script>
export default {
  name: 'CityAlphabet',
  props: {
    cities: Object
  },
  updated () {
    if (this.letters.length > 0) {
      this.firstLetter = this.letters[0]
      this.startY = this.$refs[this.firstLetter][0].offsetTop
      this.itemHeight = this.$refs[this.firstLetter][0].offsetHeight
    }
  },
  data () {
    return {
      touchState: false,
      startY: 0,
      firstLetter: '',
      itemHeight: 0
    }
  },
  computed: {
    letters () {
      const letters = []
      for (let key in this.cities) {
        letters.push(key)
      }
      return letters
    }
  },
  methods: {
    goTopage: function (letter) {
      this.$emit('goToItem', letter)
    },
    handleTouchStart () {
      this.touchState = true
    },
    handleTouchMove (e) {
      if (this.touchState) {
        if (this.itemHeight === 0) {
          return
        }
        let dom = document.elementFromPoint(e.targetTouches[0].clientX, e.targetTouches[0].clientY)
        if (!dom) {
          return
        }
        let index = Math.floor((dom.offsetTop - this.startY) / this.itemHeight)
        if (index >= 0 && index < this.letters.length) {
          this.$emit('goToItem', this.letters[index])
        }
      }
    },
    handleTouchEnd () {
      this.touchState = false
    }
  }
}
</script>

<style lang="stylus" scoped>
  @import '~styles/varibles.styl'
  .list
    display: flex
    flex-direction: column
    justify-content: center
    position: absolute
    top: 1.58rem
    right: 0
    bottom: 0
    width: .4rem
    .item
      line-height: .4rem
      text-align: center
      color: $bgColor
</style>
